<template>

  <div class="app-container">
    <div><h2 style="text-align: center;">课程信息</h2></div>

    <div style="margin-left: 10%;margin-right: 10%;">
      <el-steps :active="1">
        <el-step title="课程基本信息"></el-step>
        <el-step title="课程大纲"></el-step>
        <el-step title="发布"></el-step>
      </el-steps>
    </div>

    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>

      <!-- 所属分类：级联下拉列表 -->
      <el-form-item label="课程类别">
        <!-- 一级分类 -->
         <el-select v-model="courseInfo.subjectParentId" placeholder="一级分类" @change="getTwoSubject">
           <el-option v-for="subject in subjectOneList" :key="subject.id" :label="subject.title" :value="subject.id"/>
         </el-select>

        <!-- 二级分类 -->
        <el-select v-model="courseInfo.subjectId" placeholder="二级分类">
           <el-option v-for="subject in subjectTwoList" :key="subject.id" :label="subject.title" :value="subject.id"/>
        </el-select>
      </el-form-item>

        <!-- 课程讲师 -->
      <el-form-item label="课程讲师">
         <el-select v-model="courseInfo.teacherId" placeholder="请选择讲师">
           <el-option v-for="teacher in teacherList" :key="teacher.id" :label="teacher.name" :value="teacher.id"/>
         </el-select>
      </el-form-item>

        <el-form-item label="总课时">
         <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
       </el-form-item>

        <!-- 课程简介-->
        <el-form-item label="课程简介">
          <tinymce :height="200" v-model="courseInfo.description"/>
        </el-form-item>

        <!-- 课程封面-->
        <el-form-item label="课程封面">
          <el-upload
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :action="BASE_API+'/oss-service/oss'"
            class="avatar-uploader">
            <img :src="courseInfo.cover">
          </el-upload>
        </el-form-item>

       <el-form-item label="课程价格">
         <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/> 元
       </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" plain="true" type="primary" @click="SaveOrUpdate">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import course from '@/api/course'
  import subject from "@/api/subject"
  import Tinymce from '@/components/Tinymce'//引入Tinymce富文本编辑器

  export default {

    components: {
      Tinymce
    }, //声明组件

    data() {
      return {
        saveBtnDisabled: false, // 按钮是否禁用
        courseInfo: {// 表单数据
          id:'',
          price: 0,
          lessonNum: 0,
          // 以下解决表单数据不全时insert语句非空校验
          teacherId: '',
          subjectId: '',//二级分类ID
          subjectParentId: '',//一级分类ID
          cover: 'https://rice-college.oss-cn-shenzhen.aliyuncs.com/2020/08/07/%E5%B0%81%E9%9D%A2.jpg',
          description: ''
        },
        BASE_API: process.env.BASE_API, // 接口API地址
        teacherList: [], // 讲师列表
        subjectOneList: [], // 一级分类
        subjectTwoList: [] // 二级分类
      }
    },

    created() {
      if (this.$route.params && this.$route.params.id){
        this.courseInfo.id = this.$route.params.id
        this.getInfoById()
      }else{
        this.courseInfo = {
          id:'',
          price: 0,
          lessonNum: 0,
          // 以下解决表单数据不全时insert语句非空校验
          teacherId: '',
          subjectId: '',//二级分类ID
          subjectParentId: '',//一级分类ID
          cover: 'https://rice-college.oss-cn-shenzhen.aliyuncs.com/2020/08/07/%E5%B0%81%E9%9D%A2.jpg',
          description: ''
        }
        //初始化讲师
        this.getTeacherList()
        //初始化一级分类
        this.getOneSubject()
      }
    },

    methods: {
      //获取课程信息
      getInfoById(){
        course.getCourseInfo(this.courseInfo.id)
          .then(response => {
            this.courseInfo = response.data.courseInfo
            //查询所有分类
            subject.getSubjectList()
            .then(response2 => {
              this.subjectOneList = response2.data.list

              for (var i = 0; i < this.subjectOneList.length; i++){
                var oneSubject = this.subjectOneList[i]

                if (this.courseInfo.subjectParentId === oneSubject.id){
                  this.subjectTwoList = oneSubject.twoSubjects
                }
              }
            })
          })
      },

      //获取二级分类
      getTwoSubject(value){
        for (var i = 0; i < this.subjectOneList.length; i++){
          var oneSubject = this.subjectOneList[i]

          if (value === oneSubject.id){
            this.subjectTwoList = oneSubject.twoSubjects
            this.courseInfo.subjectId = ''
          }
        }
      },

      //查询所有一级课程分类
      getOneSubject(){
        subject.getSubjectList()
          .then(response => {
            this.subjectOneList = response.data.list
          })
      },

      //查询所有讲师
      getTeacherList(){
        course.getListTeacher()
        .then(response => {
          this.teacherList = response.data.items
        })
      },

      SaveOrUpdate(){
        if (this.courseInfo.id){
          this.updateCourse()
        }else {
          this.addCourse()
        }
      },

      //添加课程
      addCourse(){
        course.addCourseInfo(this.courseInfo)
          .then(response => {
            //提示信息
            this.$message({
              type: 'success',
              message: '添加课程信息成功',
            })
            this.$router.push({path:'/course/chapter/'+response.data.id})
          })
      },

      //修改课程
      updateCourse(){
        course.updateCourseInfo(this.courseInfo)
          .then(response => {
            //提示信息
            this.$message({
              type: 'success',
              message: '修改课程信息成功',
            })
            this.$router.push({path:'/course/chapter/'+this.courseInfo.id})
          })
      },

      //上传封面之前
      beforeAvatarUpload(file){
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },

      //上传封面成功
      handleAvatarSuccess(res,file){
        if (res.success) {
          this.courseInfo.cover = res.data.url
          // 强制重新渲染
          this.$forceUpdate()
        } else {
          this.$message.error('上传失败1（非20000）')
        }
      }
    }
  }
</script>

<style scoped>
  .tinymce-container {
     line-height: 29px;
  }
</style>
